var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var ejs = require('ejs');
var routes = require('./routes/index');
var app = express();
//var config = require("/config/config");
var params;
var utils = require(__dirname+"/utils.js");
var log4js = require('log4js');
log4js.configure(__dirname+'/config/log4js.json');
//获取该js的log
var log = log4js.getLogger("app");

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');
//app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
//对express修改默认的log类型为log4js
app.use(log4js.connectLogger(log4js.getLogger("http"), { level: 'auto' }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
//开放静态文件读取，可以直接访问public文件夹中得html等
app.use(express.static(path.join(__dirname, 'public')));



app.use('/', routes);
//routes.init({});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});
var mysqlConn;
app.initParam = function(param){
    log.info(param);
    utils.connectMysql(param.mysql)
        .then(function(conn){
            conn.on('error', function(err) {
                log.info('mysql error', err);
                if (err.code === 'PROTOCOL_CONNECTION_LOST') {
                    log.info('重连mysql...', param.mysql.host);
                    app.initParam(param)
                } else {
                    throw err;
                }
            });
            param["mysql"] = conn;
            mysqlConn = conn;
            routes.initParam(param);
        },function(err){
            log.info("数据库连接失败，启动失败");
            process.exit(0);
        });
};
//创建定时任务，保存mysql的链接正常存在
setInterval(function(){
    var sql = "select 1 from DUAL";
    mysqlConn.query(sql, [], function(err, results){
        if (!err) {
            log.info(results);
        } else {
            log.info(err);
        }
    });
},10000);

module.exports = app;
